<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能对话 - 智能招投标AI系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f5f5f5;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            width: 100%;
        }
        .chat-header {
            background-color: #fff;
            border-radius: 10px 10px 0 0;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        .chat-body {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }
        .chat-footer {
            background-color: #fff;
            border-radius: 0 0 10px 10px;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        .message {
            margin-bottom: 15px;
            max-width: 80%;
        }
        .message-user {
            align-self: flex-end;
        }
        .message-ai {
            align-self: flex-start;
        }
        .message-content {
            padding: 12px 16px;
            border-radius: 18px;
            position: relative;
        }
        .message-user .message-content {
            background-color: #0d6efd;
            color: white;
            border-bottom-right-radius: 4px;
        }
        .message-ai .message-content {
            background-color: #f0f2f5;
            color: #000;
            border-bottom-left-radius: 4px;
        }
        .message-time {
            font-size: 0.75rem;
            color: #888;
            margin-top: 5px;
            text-align: right;
        }
        .typing-indicator {
            display: inline-block;
            padding: 12px 16px;
            background-color: #f0f2f5;
            border-radius: 18px;
            border-bottom-left-radius: 4px;
            margin-bottom: 15px;
            align-self: flex-start;
        }
        .typing-indicator span {
            height: 8px;
            width: 8px;
            background-color: #888;
            display: inline-block;
            border-radius: 50%;
            animation: typing 1.3s ease-in-out infinite;
            margin: 0 1px;
        }
        .typing-indicator span:nth-child(2) {
            animation-delay: 0.15s;
        }
        .typing-indicator span:nth-child(3) {
            animation-delay: 0.3s;
        }
        @keyframes typing {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-5px);
            }
        }
        .input-group {
            position: relative;
        }
        .form-control {
            border-radius: 30px;
            padding-right: 50px;
            resize: none;
            overflow: hidden;
            height: 56px;
            max-height: 200px;
        }
        /* 发送按钮样式已移至内联样式 */
        .chat-options {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .ai-thinking {
            font-style: italic;
            color: #666;
            margin-bottom: 10px;
        }
        .message-content pre {
            background-color: rgba(0,0,0,0.05);
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
        .message-content code {
            font-family: monospace;
        }
        .message-content img {
            max-width: 100%;
            border-radius: 5px;
            margin: 10px 0;
        }
        .message-content ul, .message-content ol {
            padding-left: 20px;
        }
        .message-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 10px 0;
        }
        .message-content th, .message-content td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .message-content th {
            background-color: #f2f2f2;
        }
        .clear-chat {
            cursor: pointer;
            color: #6c757d;
        }
        .clear-chat:hover {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">智能招投标AI系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/chat">AI对话</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <div class="dropdown">
                        <button class="btn btn-outline-light dropdown-toggle" type="button" id="userDropdown" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> <span>用户</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="/profile">个人资料</a></li>
                            <li><a class="dropdown-item" href="/settings">设置</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/logout">退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <div class="chat-container">
        <div class="chat-header">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">智能AI助手</h4>
                <div>
                    <span class="clear-chat" id="clearChat" title="清空对话">
                        <i class="bi bi-trash"></i> 清空对话
                    </span>
                </div>
            </div>
        </div>
        
        <div class="chat-body" id="chatBody">
            <!-- AI欢迎消息 -->
            <div class="message message-ai">
                <div class="message-content">
                    <p>您好！我是智能招投标AI助手，可以帮您解答招投标相关问题、分析文件、提供建议等。请问有什么可以帮助您的？</p>
                </div>
                <div class="message-time">今天 12:00</div>
            </div>
            
            <!-- 消息将动态添加到这里 -->
        </div>

        <!-- 修改后的 chat-footer 部分 -->
        <div class="chat-footer">
            <div class="chat-options">
                <div>
                    <button class="btn btn-sm btn-outline-secondary me-2" id="uploadFileBtn">
                        <i class="bi bi-paperclip"></i> 上传文件
                    </button>
                </div>
            </div>
            <form id="chatForm">
                <div class="input-group position-relative">
                    <textarea class="form-control" id="messageInput" placeholder="输入您的问题..." rows="1" style="resize: none; overflow: hidden; height: 56px; max-height: 200px;"></textarea>
                    <div class="position-absolute" style="right: 8px; top: 8px; z-index: 5;">
                        <button class="btn btn-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px; padding: 0;" type="submit" aria-label="发送">
                            <i class="bi bi-send-fill"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 文件上传模态框 -->
    <div class="modal fade" id="uploadFileModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传文件</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="fileUploadForm">
                        <div class="mb-3">
                            <label for="fileUpload" class="form-label">选择文件</label>
                            <input class="form-control" type="file" id="fileUpload" name="file" required>
                            <div class="form-text">支持PDF、Word、Excel、文本文件等格式，最大50MB</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitFileUpload">上传</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            const chatBody = document.getElementById('chatBody');
            const chatForm = document.getElementById('chatForm');
            const messageInput = document.getElementById('messageInput');
            const uploadFileBtn = document.getElementById('uploadFileBtn');
            const uploadFileModal = new bootstrap.Modal(document.getElementById('uploadFileModal'));
            const submitFileUpload = document.getElementById('submitFileUpload');
            const clearChat = document.getElementById('clearChat');

            let currentMemoryId = Number(localStorage.getItem('currentMemoryId')) || Math.floor(Date.now() / 1000);
            localStorage.setItem('currentMemoryId', String(currentMemoryId));

            // 文本框自适应高度
            messageInput.addEventListener('input', function() {
                this.style.height = 'auto';
                let newHeight = this.scrollHeight;
                if (newHeight > 200) newHeight = 200;
                this.style.height = newHeight + 'px';
            });

            // 监听回车发送
            messageInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    const message = this.value.trim();
                    if (message) sendUserMessage(message);
                }
            });

            chatForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const message = messageInput.value.trim();
                if (message) sendUserMessage(message);
            });

            function sendUserMessage(message) {
                addMessage(message, 'user');
                messageInput.value = '';
                messageInput.style.height = '56px';
                showTypingIndicator();
                sendMessageToApi(message);
            }

            uploadFileBtn.addEventListener('click', () => uploadFileModal.show());

            submitFileUpload.addEventListener('click', function() {
                const fileInput = document.getElementById('fileUpload');
                if (fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    uploadFile(file);
                    uploadFileModal.hide();
                }
            });

            clearChat.addEventListener('click', function() {
                if (confirm('确定要清空所有对话记录吗？')) {
                    chatBody.innerHTML = '';
                    addMessage('您好！我是智能招投标AI助手，可以帮您解答招投标相关问题、分析文件、提供建议等。请问有什么可以帮助您的？', 'ai');
                    currentMemoryId = Math.floor(Date.now() / 1000);
                    localStorage.setItem('currentMemoryId', String(currentMemoryId));
                }
            });

            function addMessage(content, sender) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message message-${sender}`;

                const messageContent = document.createElement('div');
                messageContent.className = 'message-content';
                messageContent.innerHTML = sender === 'ai' ? parseMarkdown(content) : content;

                const messageTime = document.createElement('div');
                messageTime.className = 'message-time';
                const now = new Date();
                messageTime.textContent = `今天 ${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}`;

                messageDiv.appendChild(messageContent);
                messageDiv.appendChild(messageTime);
                chatBody.appendChild(messageDiv);
                chatBody.scrollTop = chatBody.scrollHeight;
            }

            function parseMarkdown(content) {
                let text = content;
                text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
                text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
                text = text.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');
                text = text.replace(/\n/g, '<br>');
                return text;
            }

            function showTypingIndicator() {
                const typingDiv = document.createElement('div');
                typingDiv.className = 'typing-indicator';
                typingDiv.id = 'typingIndicator';
                for (let i=0;i<3;i++){
                    const dot = document.createElement('span');
                    typingDiv.appendChild(dot);
                }
                chatBody.appendChild(typingDiv);
                chatBody.scrollTop = chatBody.scrollHeight;
            }

            function hideTypingIndicator() {
                const indicator = document.getElementById('typingIndicator');
                if (indicator) indicator.remove();
            }

            // SSE 流式发送消息
            function sendMessageToApi(message) {
                const memoryId = currentMemoryId;

                hideTypingIndicator();

                // 创建新的AI消息容器
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message message-ai';
                const messageContent = document.createElement('div');
                messageContent.className = 'message-content';
                messageDiv.appendChild(messageContent);

                const messageTime = document.createElement('div');
                messageTime.className = 'message-time';
                const now = new Date();
                messageTime.textContent = `今天 ${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}`;
                messageDiv.appendChild(messageTime);

                chatBody.appendChild(messageDiv);
                chatBody.scrollTop = chatBody.scrollHeight;

                const url = `/chat/stream-flux?question=${encodeURIComponent(message)}&memoryId=${memoryId}`;
                const es = new EventSource(url);

                es.addEventListener('message', (event) => {
                    try {
                        const obj = JSON.parse(event.data);
                        const chunk = obj.d || '';
                        appendAIResponse(messageContent, chunk);
                    } catch (_) {
                        appendAIResponse(messageContent, event.data);
                    }
                    chatBody.scrollTop = chatBody.scrollHeight;
                });

                es.addEventListener('done', () => {
                    es.close();
                });

                es.onerror = (e) => {
                    console.error('SSE error:', e);
                    es.close();
                    appendAIResponse(messageContent, '<br><span style="color:red;">连接中断，请重试。</span>');
                    chatBody.scrollTop = chatBody.scrollHeight;
                };
            }

            function appendAIResponse(container, chunk) {
                container.innerHTML += parseMarkdown(chunk);
            }

            function uploadFile(file) {
                addMessage(`我上传了文件：${file.name}`, 'user');
                showTypingIndicator();
                setTimeout(() => {
                    hideTypingIndicator();
                    const aiResponse = `我已收到您上传的文件 **${file.name}**，文件大小 ${(file.size/1024).toFixed(2)} KB。\n\n请问希望我对这个文件做什么分析？`;
                    addMessage(aiResponse, 'ai');
                }, 2000);
            }
        });
    </script>
</body>
</html>